#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn=51, maxm=400, maxk=820000;
int n, m, a[maxn+1][maxm+1], ansn, ans[maxk+1][2];

void mv(int x, int y) {
    ansn++;
    ans[ansn][0]=x, ans[ansn][1]=y;
    a[y][++a[y][0]]=a[x][a[x][0]];
    a[x][a[x][0]--] = 0;
}

void solve(int l, int r) {
    if (l<r) {
        static int t[maxn+1];
        int mid=(l+r)/2;
        for (int i=l; i<=mid; i++) {
            t[i]=0;
            for (int j=1; j<=m; j++) t[i] += a[i][j]>mid;
        }
        for (int i=mid+1; i<=r; i++) {
            t[i]=0;
            for (int j=1; j<=m; j++) t[i] += a[i][j]<=mid;
        }

        for (int i=l, j=mid+1; i<=mid && j<=r; ) {
            for (; i<=mid && !t[i]; i++);
            for (; j<=r && !t[j]; j++);
            if (i>mid || j>r) break;
            for (int k=1; k<=t[i]; k++) mv(j, n+1);
            for (int k=m; k; k--) {
                if (a[i][k]>mid) mv(i, j);
                else mv(i, n+1);
            }
            for (int k=m; k>t[i]; k--) mv(n+1, i);
            for (int k=m; k>m-t[i]; k--) mv(j, i);
            for (int k=a[j][0]; k; k--) mv(j, n+1);
            for (int k=m; k>m-t[i]; k--) mv(i, j);
            for (int k=m; k; k--) {
                if (a[i][0]==m || (a[n+1][k]>mid && a[j][0]<m)) mv(n+1, j);
                else mv(n+1, i);
            }

            t[i] = t[j] = 0;
            for (int k=1; k<=m; k++) t[i]+=a[i][k]>mid, t[j]+=a[j][k]<=mid;
        }

        solve(l, mid);
        solve(mid+1, r);
    }
}

int main() {
    freopen("ball.in", "r", stdin);
    freopen("ball.out", "w", stdout);

    scanf("%d %d", &n, &m);
    for (int i=1; i<=n; i++) {
        a[i][0] = m;
        for (int j=1; j<=m; j++) {
            scanf("%d", a[i]+j);
        }
    }

    solve(1, n);

    printf("%d\n", ansn);
    for (int i=1; i<=ansn; i++) printf("%d %d\n", ans[i][0], ans[i][1]);

    fclose(stdin);
    fclose(stdout);
    return 0;
}
